#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"../include/main.h"
#include"../include/removefile.h"
#include"../include/mount_vfs.h"
#include"../include/narrtree.h"
#include"../include/hash.h"
#include"../include/bst.h"
#include"../include/vfs_errorcodes.h"
#include"../include/create_vfs.h"

void remove_file(char filepath[])
{
	fdesc *mkdescd;
	ntree *temphead;
	char temp[MAX_PATH];
	char *fname,*pchh;
	int i=0,listd,blk;
	if(mounted==0)
		printf("%s_FAILURE %s\n",glb_command,ERR_VFS_REMOVEFILE_02);
	else
	{
		while(filepath[i]!='\0')
		{
			temp[i]=filepath[i];
			i++;
		}
		temp[i]='\0';

		pchh = strtok (temp,"/");
		while (pchh != NULL)
		{
			fname=pchh;
			pchh = strtok (NULL, "/");
		}
		mkdescd=(fdesc *)malloc(sizeof(fdesc));
		strcpy(mkdescd->filepath,filepath);
		if(!strcmp(filepath,"/"))
		{
			printf("%s_FAILURE_%s\n",glb_command,ERR_VFS_REMOVEFILE_01);
		}
		else
		{
			strcpy(mkdescd->filename,fname);

			mkdescd->filetype=0;
			mkdescd->file_size=0;
		        mkdescd->blk_num=0;
			listd=deletion(mkdescd);
			if(listd==0)
				printf("%s_FAILURE %s\n",glb_command,ERR_VFS_REMOVEFILE_01);
			else
			{
				temphead=delete_ntree(head,mkdescd);
				if(temphead != NULL)
				{
					//head=temphead;
					blk=temphead->file_desc->blk_num;
					for(i=0;i<glb_blk_num;i++)		
					if(*(block_arr+i)==blk)
					{
						*(block_arr+i)=blk+size_of_vfs;
						break;
					}
					local_used_fd--;
					printf("removefile_SUCCESS\n");
					//printf("local_max_fd=%d local_used_fd=%d\n",local_max_fd,local_used_fd);
				}
			}
			free(mkdescd);
		}
	}
}
